package com.kkkk.rest.common.util;

import jakarta.annotation.Resource;
import org.springframework.context.MessageSource;
import org.springframework.context.MessageSourceResolvable;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.stereotype.Component;

import java.util.Locale;

@Component
public class I18nUtils {

    @Resource
    private MessageSource messageSource;

//    private final static Logger log = LoggerFactory.getLogger(I18nUtils.class);

    /**
     * 根据CODE查询，默认无通配参数
     *
     * @Description:
     * @param: code
     */
    public String getMessage(String code) {
        return getMessage(code, null, getLocal());
    }

    /**
     * 根据CODE查询
     *
     * @Description:
     * @param: code :资源key
     * @param: locale : 请求头参数language
     */
    public String getMessage(String code, String locale) {
        if (Locale.ENGLISH.getLanguage().equals(locale)) {
            return getMessage(code, null, Locale.US);
        } else {
            return getMessage(code, null, Locale.SIMPLIFIED_CHINESE);
        }
    }

    /**
     * 根据CODE和args查询，Local跟随当前cookie
     *
     * @Description:
     * @param: code
     * @param: args 通配符的参数
     */
    public String getMessage(String code, Object[] args) {
        return getMessage(code, args, getLocal());
    }

    public String getMessage(String code, Object[] args, String defaultMessage, Locale locale) {
        return messageSource.getMessage(code, args, defaultMessage, locale);
    }

    public String getMessage(String code, Object[] args, Locale locale) {
        try {
            return messageSource.getMessage(code, args, locale);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }

    }

    public String getMessage(MessageSourceResolvable resolvable, Locale locale) {
        try {
            return messageSource.getMessage(resolvable, locale);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }

    }

    /**
     * 解析用户区域
     *
     * @return
     */
    public Locale getLocal() {
        return LocaleContextHolder.getLocale();
    }
}
